package com.sz.web.common.initialize;


import com.sz.web.account.entity.AccountFunction;
import com.sz.web.account.entity.AccountRole;
import com.sz.web.account.entity.AccountRoleFunction;
import com.sz.web.account.enums.FunctionStatus;
import com.sz.web.account.mapper.AccountFunctionMapper;
import com.sz.web.account.mapper.AccountRoleFunctionMapper;
import com.sz.web.account.mapper.AccountRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * 功能表初始化
 */
@Component
public class FunctionInit {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    @Resource
    private AccountFunctionMapper accountFunctionMapper;
    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private AccountRoleFunctionMapper accountRoleFunctionMapper;

    /**
     * 管理员路由权限初始化
     */
    public void funciontUrlInit() {

        //1.获取所有controller路由
        Map<RequestMappingInfo, HandlerMethod> maps = new HashMap<>();
        maps = requestMappingHandlerMapping.getHandlerMethods();

        //2.将路由列表初始化进功能表中
        for (Map.Entry<RequestMappingInfo, HandlerMethod> map : maps.entrySet()) {
            Set<String> urls = map.getKey().getPatternsCondition().getPatterns();
            String controlUrl = String.valueOf(urls.toArray()[0]);
            if (accountFunctionMapper.selectCountByControlUrl(controlUrl) > 0){
                continue;
            }
            AccountFunction accountFunction = new AccountFunction();
            accountFunction.setFunctionName("未定义");
            accountFunction.setStatus(FunctionStatus.USING.getStatus());
            accountFunction.setControlUrl(controlUrl);
            accountFunctionMapper.insert(accountFunction);

            //3.将所有路由初始化进管理员角色中
            AccountRole accountRole = accountRoleMapper.selectByRoleName("管理员");
            if(accountRole != null){
                int roleId = accountRole.getId();
                int functionId = accountFunction.getId();
                AccountRoleFunction accountRoleFunction = new AccountRoleFunction();
                accountRoleFunction.setRoleId(roleId);
                accountRoleFunction.setFunctionId(functionId);
                accountRoleFunctionMapper.insert(accountRoleFunction);
            }
        }
    }
}
